$(function(){
	var $tabList=$("#tab_list"),$pagebar=$("#pagebar ul"),$pageInfo=$("#page_info"),
		pageNo=1,pageSize=10,count=0;//初始值
	/**---------------封装分页方法,count:总条目数,pageNo:当前页---------------*/
	function pageit(count){
		$pagebar.empty();
		//首页和上一页
		if(pageNo==1){
			$pagebar.append("<li id='start_page' class='disabled'><a href='javascript:void(0);'>首页</a></li>");
			$pagebar.append("<li id='prev_page'  class='disabled'><a href='javascript:void(0);'>上一页</a></li>");
		}else{
			$pagebar.append("<li id='start_page' pn=1><a href='javascript:void(0);'>首页</a></li>");
			$pagebar.append("<li id='prev_page' pn="+(pageNo-1)+"><a href='javascript:void(0);'>上一页</a></li>");
		}
		var tmp=parseInt(count/10);
		var page_size=count%10==0?(tmp):(tmp+1);//总页数
		//中间数字页
		if(page_size<=5){
			//如果小于5页,则全部显示
			for(var i = 0; i <page_size; i++) {
				if(i==pageNo-1){
					$pagebar.append("<li pn="+(i+1)+" class='active'><a href='javascript:void(0);'>"+(i+1)+"</a></li>");
				}else{
					$pagebar.append("<li pn="+(i+1)+"><a href='javascript:void(0);'>"+(i+1)+"</a></li>");
				}
			}
		}else{
			//如果总页数大于5页,显示当前页和前后各两页以及两个...符号
			if(pageNo<3){
				for(var i = 0; i <5; i++) {
					if(i==pageNo-1){
						$pagebar.append("<li pn="+(i+1)+" class='active'><a href='javascript:void(0);'>"+(i+1)+"</a></li>");
					}else{
						$pagebar.append("<li pn="+(i+1)+"><a href='javascript:void(0);'>"+(i+1)+"</a></li>");
					}
				}
				$pagebar.append("<li class='disabled'><a href='javascript:void(0);'>...</a></li>");
			}else if(pageNo>page_size-2){
				$pagebar.append("<li class='disabled'><a href='javascript:void(0);'>...</a></li>");
				for(var i = page_size-5; i <page_size; i++) {
					if(i==pageNo-1){
						$pagebar.append("<li pn="+(i+1)+" class='active'><a href='javascript:void(0);'>"+(i+1)+"</a></li>");
					}else{
						$pagebar.append("<li pn="+(i+1)+"><a href='javascript:void(0);'>"+(i+1)+"</a></li>");
					}
				}
			}else{
				for (var i = pageNo-3; i <pageNo+2; i++) {
					if(i==pageNo-1){
						$pagebar.append("<li pn="+(pageNo)+" class='active'><a href='javascript:void(0);'>"+(i+1)+"</a></li>");
					}else{
						$pagebar.append("<li pn="+(i+1)+"><a href='javascript:void(0);'>"+(i+1)+"</a></li>");
					}
				}
			}
		}
		//下一页和末页
		if(page_size==0||pageNo==page_size){
			$pagebar.append("<li id='next_page' class='disabled'><a href='javascript:void(0);'>下一页</a></li>");
			$pagebar.append("<li id='end_page' class='disabled'><a href='javascript:void(0);'>末页</a></li>");
		}else{
			$pagebar.append("<li id='next_page' pn="+(pageNo+1)+"><a href='javascript:void(0);'>下一页</a></li>");
			$pagebar.append("<li id='end_page' pn="+page_size+"><a href='javascript:void(0);'>末页</a></li>");
		}
		
		//绑定事件
		$pagebar.find("li").not(".disabled").on("click",function(){
			pageNo=parseInt($(this).attr("pn"));//更新当前页码
			reloadList();
		});
		//分页信息条
		$pageInfo.find("span").each(function(i,k){
			if(i==0){
				if(page_size==0){
					$(k).html(0);
				}else{
					$(k).html((pageNo-1)*10+1);
				}
			}else if(i==1){
				$(k).html(count>pageNo*10?pageNo*10:count);
			}else{
				$(k).html(count);
			}
		});
	}
    var $formSearch=$("#search_form"),$searchPro=$formSearch.find("[name=search_province]"),
    	$searchCity=$formSearch.find("[name=search_city]"),$searchCounty=$formSearch.find("[name=search_county]");
	/**------------------加载列表---------------------*/
	var params={"pageNo":1,"pageSize":pageSize,"province":null,"city":null,"county":null};
	function reloadList(){
		params.pageNo=pageNo;
		params.pageSize=pageSize;
		params.province=$searchPro.val();
		params.city=$searchCity.val();
		params.county=$searchCounty.val();
		$.get(serverURL+"hospital/list",params,function(data){
			try {
				if(data.code==0){
					data=data.data;
					$tabList.find("tbody").empty();
					count=data.pagination.totalCount;
					if(count>0){
						var html="";
						$.each(data.list,function(i,k){
							var loc=k.province+k.city+k.county+k.location;
							html+="<tr>" +
								"<td id='pkc'><input type='checkbox' id='"+k.id+"' class='checkbox' col='"+i+"'></td>" +
								"<td>"+((pageNo-1)*10+i+1)+"</td>" +
								"<td>"+k.name+"</td>"+ 
								"<td>"+(loc?loc:"暂无")+"</td>"+ 
								"<td>"+(k.level?k.level:"暂无")+"</td>"+ 
							"</tr>";
						});
						$tabList.find("tbody").append(html);
						$tabList.find("tr").dblclick(function(){
							openEditModal($(this).find("#pkc input").attr("id"));
						});
//					$(".tools button").removeAttr("disabled");
					}else{
						$tabList.find("tbody").append("<tr><td colspan="+$("thead th").length+">无数据</td></tr>");
//					$(".tools button").not(".btn-default").attr("disabled","disabled");
					}
					pageit(count);//重绘工具栏
				}else if(data.code!=-1){
					alert("数据加载出错，请稍后重试");
				}
			} catch (e) {
				alert("数据加载出错，请稍后重试");
			}
		});
	}
	reloadList();
	//全选与取消全选
	$("#pkall").change(function(){
		if($(this).prop("checked")){
			$tabList.find("#pkc :checkbox").prop("checked",true);
		}else{
			$tabList.find("#pkc :checkbox").prop("checked",false);
		}
	});
	//获取选中的行
	function getSelectedCols(){
		return $tabList.find("#pkc :checkbox").filter(":checked");
	}
	
	/**------------- 增加医院 -----------------*/
	var $formAdd=$("#form_add"),$addName=$formAdd.find("[name=name]"),
		$addLevel=$formAdd.find("[name=level]"),$addLocation=$formAdd.find("[name=location]"),
		$addPro=$formAdd.find("[name=province]"),$addCity=$formAdd.find("[name=city]"),$addCounty=$formAdd.find("[name=county]");	
	function checkAddForm(){
    	if(!$addName.val()){
    		warnInput($addName);
    		return false;
    	}
    	if($addName.val().length>30){
    		alert("医院名称不能超过30个字符");
    		return false;
    	}
    	if(!$addLevel.val()){
    		warnInput($addLevel);
    		return false;
    	}
     	if($addCounty.val()==0){
    		warnInput($addCounty);
    		return false;
    	}
    	if($addLocation.val()==0){
    		warnInput($addLocation);
    		return false;
    	}
    	if($addLocation.val().length>80){
    		alert("详细位置不能超过80个字符");
    		return false;
    	}
    	return true;
	}   
	$("#btn_confirm_add").click(function() {
    	if(checkAddForm()){
    		$.post(serverURL+"hospital/add",{"name":$addName.val(),"level":$addLevel.val(),
				"location":$addLocation.val(),"county":$addCounty.val()},function(data){
					if(data.code==0){
						alert("医院信息增加成功！");
						$("#modal_add").modal("hide");
						$formAdd.get(0).reset();
						reloadList();
					}else{
						alert("医院增加失败");
					}
			});
    	}
	});
	
    /**--------------增加窗口中的省市区三级联动处理----------------*/
    $addPro.change(function(){
    	districtAdd.reloadCity($(this).val());
    });
    $addCity.change(function(){
    	districtAdd.reloadCounty($(this).val());
    });
    var districtAdd={
    	clearCity:function(){$addCity.find("option[value!=0]").remove();},
    	clearCounty:function(){$addCounty.find("option[value!=0]").remove();},
    	reloadCity:function(pid){
			districtAdd.clearCity();
			districtAdd.clearCounty();
    		if(pid!=0){
    			$.ajax({   //此处用同步处理，避免出现val()比reload早的问题
    				url:serverURL+"district/city/"+pid,
    				type:"get",
    				async:false,
    				success:function(data){
    					if(data.code==0){
    						var html="";
    						$.each(data.data,function(i,k){
    							html+="<option value='"+k.id+"'>"+k.dName+"</option>";
    						});
    						$addCity.append(html);
    					}else if(data.code!=-1){
    						alert("城市数据加载失败");
    					}
    				}
    			});
    		}
        },
        reloadCounty:function(cid){
			districtAdd.clearCounty();
        	if(cid!=0){
        		$.ajax({
        			url:serverURL+"district/county/"+cid,
        			type:"get",
        			async:false,
        			success:function(data){
        				if(data.code==0){
        					var html="";
        					$.each(data.data,function(i,k){
        						html+="<option value='"+k.id+"'>"+k.dName+"</option>";
        					});
        					$addCounty.append(html);
        				}else if(data.code!=-1){
        					alert("县/区数据加载失败");
        				}
        			}
        		});
        	}
        }
    };
    /**-------------修改医院信息-----------------*/
    var $formEdit=$("#form_edit"),$editId=$formEdit.find("[name=id]"),$editName=$formEdit.find("[name=name]"),
    	$editLevel=$formEdit.find("[name=level]"),$editLocation=$formEdit.find("[name=location]"),
    	$editPro=$formEdit.find("[name=province]"),$editCity=$formEdit.find("[name=city]"),$editCounty=$formEdit.find("[name=county]");
    function openEditModal(id){
    	$formEdit.get(0).reset();
    	//给隐藏域id赋值
    	$editId.val(id);
    	
    	//从后台获取该条记录所有信息
    	$.get(serverURL+"hospital/get",{"id":id},function(data){
    		if(data.code==0){
    			data=data.data;
    			$editName.val(data.name);
    			$editLevel.val(data.level);
    			$editLocation.val(data.location);
    			data.province?$editPro.val(data.province):null;
    			
    			//此处用同步处理，避免出现val()比reload早的问题
    			data.province?district.reloadCity(data.province):null;
    			data.city?$editCity.val(data.city):null;
    			data.city?district.reloadCounty(data.city):null;
    			data.county?$editCounty.val(data.county):null;
    			
    			$("#modal_edit").modal("show");
    		}else if(data.code!=-1){
    			alert("医生信息加载失败");
    		}
    	});	
    }
    $("#btn_edit").click(function(){
    	//获取选中的行		
    	var $curCol=getSelectedCols();
    	if($curCol.length!=1){
    		alert("请选择一条记录修改,也可双击一行进行选择");
    		return;
    	}
    	var id=$curCol[0].id;
    	openEditModal(id);
    });
    function checkEditForm(){
    	if(!$editName.val()){
    		warnInput($editName);
    		return false;
    	}
    	if($editName.val().length>30){
    		alert("医院名称不能超过30个字符");
    		return false;
    	}
    	if(!$editLevel.val()){
    		warnInput($editLevel);
    		return false;
    	}
    	if($editCounty.val()==0){
    		warnInput($editCounty);
    		return false;
    	}
    	if($editLocation.val()==0){
    		warnInput($editLocation);
    		return false;
    	}
    	if($editLocation.val().length>80){
    		alert("详细位置不能超过80个字符");
    		return false;
    	}
    	return true;
    }   
    $("#btn_confirm_edit").click(function(){
    	//表单验证
    	if(checkEditForm()){
			$.post(serverURL+"hospital/edit",{"id":$editId.val(),"name":$editName.val(),
				"level":$editLevel.val(),"location":$editLocation.val(),"county":$editCounty.val()},function(data){
				if(data.code==0){
					alert("修改成功");
					$('#modal_edit').modal('hide');//隐藏模态框
					$formEdit.get(0).reset();
					reloadList();
				}else if(data.code!=-1){
					alert("修改失败，请稍后重试");
				}
			});
		}
    });
    /**--------------修改窗口中的省市区三级联动处理----------------*/
    $editPro.change(function(){
    	district.reloadCity($(this).val());
    });
    $editCity.change(function(){
    	district.reloadCounty($(this).val());
    });
    var district={
    	clearCity:function(){$editCity.find("option[value!=0]").remove();},
    	clearCounty:function(){$editCounty.find("option[value!=0]").remove();},
    	reloadCity:function(pid){
			district.clearCity();
			district.clearCounty();
    		if(pid!=0){
    			$.ajax({   //此处用同步处理，避免出现val()比reload早的问题
    				url:serverURL+"district/city/"+pid,
    				type:"get",
    				async:false,
    				success:function(data){
    					if(data.code==0){
    						var html="";
    						$.each(data.data,function(i,k){
    							html+="<option value='"+k.id+"'>"+k.dName+"</option>";
    						});
    						$editCity.append(html);
    					}else if(data.code!=-1){
    						alert("城市数据加载失败");
    					}
    				}
    			});
    		}
        },
        reloadCounty:function(cid){
			district.clearCounty();
        	if(cid!=0){
        		$.ajax({
        			url:serverURL+"district/county/"+cid,
        			type:"get",
        			async:false,
        			success:function(data){
        				if(data.code==0){
        					var html="";
        					$.each(data.data,function(i,k){
        						html+="<option value='"+k.id+"'>"+k.dName+"</option>";
        					});
        					$editCounty.append(html);
        				}else if(data.code!=-1){
        					alert("县/区数据加载失败");
        				}
        			}
        		});
        	}
        }
    };
    /**--------------省市区查询过滤----------------*/
    $.get(serverURL+"district/province",function(data){
    	var html="";
    	$.each(data.data,function(i,k){
    		html+="<option value='"+k.id+"'>"+k.dName+"</option>";
    	});
    	$addPro.append(html);
    	$editPro.append(html);
    	$searchPro.append(html);
    });
    $searchPro.change(function(){
    	search_district.reloadCity($(this).val());
    	reloadList();
    });
    $searchCity.change(function(){
    	search_district.reloadCounty($(this).val());	
    	reloadList();
    });  
    $searchCounty.change(function(){
    	reloadList();
    });  
    var search_district={
    	clearCity:function(){$searchCity.find("option[value!=0]").remove();},
    	clearCounty:function(){$searchCounty.find("option[value!=0]").remove();},
    	reloadCity:function(pid){
    		search_district.clearCity();
    		search_district.clearCounty();
    		if(pid!=0){
    			$.ajax({   //此处用同步处理，避免出现val()比reload早的问题
    				url:serverURL+"district/city/"+pid,
    				type:"get",
    				async:false,
    				success:function(data){
    					if(data.code==0){
    						var html="";
    						$.each(data.data,function(i,k){
    							html+="<option value='"+k.id+"'>"+k.dName+"</option>";
    						});
    						$searchCity.append(html);
    					}else if(data.code!=-1){
    						alert("城市数据加载失败");
    					}
    				}
    			});
    		}
        },
        reloadCounty:function(cid){
        	search_district.clearCounty();
        	if(cid!=0){
        		$.ajax({
        			url:serverURL+"district/county/"+cid,
        			type:"get",
        			async:false,
        			success:function(data){
        				if(data.code==0){
        					var html="";
        					$.each(data.data,function(i,k){
        						html+="<option value='"+k.id+"'>"+k.dName+"</option>";
        					});
        					$searchCounty.append(html);   
        				}else if(data.code!=-1){
        					alert("县/区数据加载失败");
        				}
        			}
        		});
        	}
        }
    };
});